
package com.amado.course35Concurrent;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/**
 * startSignal startSignal组合
 * 测试10个线程并发
 */
public class S01CountDownLatchTest3 {

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch startSignal = new CountDownLatch(1);
		CyclicBarrier cyclicBarrier = new CyclicBarrier(4,()->{
			System.out.println("最后完成任务");
			startSignal.countDown();
		});
		//相当于运动动陆续上场
		for (int i = 0; i < 4; i++) {
			new Thread(() -> {
				try {
					int longTime = new Random().nextInt(1000);
					System.out.println(Thread.currentThread().getName()+"睡觉"+longTime);
					Thread.sleep(longTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				try {
					System.out.println("运行完成"+ Thread.currentThread().getName());
					cyclicBarrier.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (BrokenBarrierException e) {
					e.printStackTrace();
				}
			}).start();
		}
		System.out.println("countdown");
		System.out.println("主线程等待");
		startSignal.await();
		System.out.println("执行主线程");

	}
}
